from django.db import models
from django.utils.module_loading import import_string


class Comment(models.Model):
    STATUS_NORMAL = 1
    STATUS_DELETE = 0
    STATUS_ITEMS = (
        (STATUS_NORMAL, 'Normal'),
        (STATUS_DELETE, 'Delete')
    )
    target = models.CharField(max_length=100, verbose_name='评论目标')
    content = models.CharField(max_length=2000, verbose_name='Content')
    nickname = models.CharField(max_length=50, verbose_name='Nick Name')
    website = models.URLField(verbose_name='Website', blank=True)
    email = models.EmailField(verbose_name='Email')
    status = models.PositiveIntegerField(default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name='Status')
    created_time = models.DateTimeField(auto_now_add=True, editable=False, verbose_name='Create Time')

    class Meta:
        verbose_name = verbose_name_plural = 'Comment Table'

    @classmethod
    def get_by_target(cls, target):
        return cls.objects.filter(target=target, status=cls.STATUS_NORMAL)

    @property
    def post_title(self):
        try:
            _, object_name, id_html = self.target.split('/')
            obj_id, html = id_html.split('.')
            object_name = object_name.capitalize()
            obj_cls = import_string('blog.models.'+object_name)
            obj = obj_cls.objects.get(pk=obj_id)
        except Exception as e:
            print('============================comment: {} can not find the target:{}, error:{}'.format(self.pk, self.target, str(e)))
            return '未知'
        return obj.title
